
package com.friendsystem.controller;

import com.friendsystem.dao.UserDao;
import com.friendsystem.model.User;
import com.friendsystem.service.FriendService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/friend")
public class FriendServlet extends HttpServlet {
    private FriendService friendService = new FriendService();

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        String userId = request.getParameter("userId");

        try (UserDao userDao = new UserDao()) {
            if ("recommend".equals(action)) {
                // 获取好友推荐
                List<User> recommendations = friendService.getFriendRecommendations(userId);
                request.setAttribute("recommendations", recommendations);
                request.getRequestDispatcher("/recommendations.jsp").forward(request, response);
            } else if ("search".equals(action)) {
                // 搜索好友
                String username = request.getParameter("username");
                User user = userDao.getUserByUsername(username);
                request.setAttribute("searchResult", user);
                request.getRequestDispatcher("/searchResult.jsp").forward(request, response);
            }
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        String userId = request.getParameter("userId");
        String friendId = request.getParameter("friendId");

        if ("add".equals(action)) {
            friendService.sendFriendRequest(userId, friendId);
            response.sendRedirect("friend?action=recommend&userId=" + userId);
        } else if ("accept".equals(action)) {
            friendService.acceptFriendRequest(friendId, userId);
            response.sendRedirect("friend?action=requests&userId=" + userId);
        } else if ("reject".equals(action)) {
            friendService.rejectFriendRequest(friendId, userId);
            response.sendRedirect("friend?action=requests&userId=" + userId);
        }
    }
}